# coding: utf8
import ast, copy

background = '#FFBBC1'

def delete():
    rules = Rules()
    del rules.rules[ast.literal_eval(request.args[0])]
    rules.commit()
    return rules.get_as_table()
    
def add():
    i = ast.literal_eval(request.args[0])
    form = Rule().make_form()
    if form.process().accepted:
        rules = Rules()
        rules.rules.insert(i, Rule(form = form))
        response.js = make_js(i)
        rules.commit()
        return rules.get_as_table()
    return form

def edit():
    i = ast.literal_eval(request.args[0])
    rules = Rules()
    form = rules.rules[i].make_form()
    if form.process().accepted:
        rules.rules[i] = Rule(form = form)
        response.js = make_js(i)
        rules.commit()
        return rules.get_as_table()
    return form
 
    
def duplicate():
    rules = Rules()
    i = ast.literal_eval(request.args[0])
    rules.rules.insert(i, copy.copy(rules.rules[i]))
    response.js = make_js(i)
    rules.commit()
    return rules.get_as_table()

def up():
    rules = Rules()
    i = ast.literal_eval(request.args[0])
    if i > 0:
        rules.rules[i - 1], rules.rules[i] = rules.rules[i], rules.rules[i - 1]
        response.js = make_js(i - 1)
        rules.commit()
    return rules.get_as_table()

def down():
    rules = Rules()
    i = ast.literal_eval(request.args[0])
    if i < len(rules.rules) - 1:
        rules.rules[i + 1], rules.rules[i] = rules.rules[i], rules.rules[i + 1]
        response.js = make_js(i + 1)
        rules.commit()
    return rules.get_as_table()
    
def make_js(i):
    return 'jQuery("#rule_{}").css("background-color", "{}");'.format(i, background)
